/**
 * 打印数据处理
 *
*/
import { format } from '@/filters/date';
import { getConfigData } from '@/components/Common/relatedProcess/data';
import { processCommonStatus } from '@/filters/status';
import { taskType as getTaskType, flowStatus } from '@/filters/status';
import { strJsonParse } from '@/utils';
import { forEachFormOptions } from '@/utils/formMakeUtils.js';

export default {
  computed: {
    printConfig() {
      let formOptions = this.formOptions;
      formOptions = _.cloneDeep(formOptions);
      if (!formOptions.list) return null;
      const config = this.getPrintConfig(formOptions);
      return config;
    },
    printData() {
      let formOptions = this.formOptions;
      formOptions = _.cloneDeep(formOptions);
      if (!formOptions.list) return {};
      const data = this.getPrintData(formOptions);
      data.processStatus = formOptions.processStatus;
      return data;
    }
  },
  methods: {
    /**
     * 打印数据处理
     */
    getPrintConfig(formOptions) {
      const config = { title: this.title, config: [] };
      this.getBasePrintConfig(formOptions.list, config);
      config.config.push({ subTitle: '审批流程', type: 'process' });
      return config;
    },
    getBasePrintConfig(list, config) {
      forEachFormOptions(list, (i) => {
        if (!['grid'].includes(i.type) && i.options && !i.options.printHide) {
          const cur = i;
          if (['subform', 'linkForm', 'associatedApproval'].includes(cur.type)) {
            const tableConfig = this.getTablePrintConfig(cur);
            tableConfig && config.config.push(tableConfig);
          } else if (cur.type === 'title') {
            config.config.push({ subTitle: cur.name, type: 'form' });
          } else {
            const lastIndex = config.config.length - 1;
            const baseFieldData = { label: cur.name, keyword: cur.key, type: cur.type };
            // 取出 config 中的最后一项，如果这项存在且type为 form，那么直接把数据插入到其 children 中
            // 如果不存在，则创建一个标题为空的 form 配置
            if (lastIndex >= 0 && config.config[lastIndex] && config.config[lastIndex].type === 'form') {
              const children = config.config[lastIndex].children;
              const lastList = children && children.length && children[children.length - 1].list;
              // 1: 在 children 的最后一项中存在list且长度为 2，则在 children 中插入新数据，因为一行最多展示两个
              // 2: 在 children 的最后一项中存在list，但是长度不满 2，则在这个 list中插入一条数据
              // 3: children 不存在
              if (lastList && lastList.length === 2) {
                children.push({ list: [baseFieldData] });
              } else if (lastList) {
                lastList.push(baseFieldData);
              } else {
                config.config[lastIndex].children = [{ list: [baseFieldData] }];
              }
            } else {
              config.config.push({ subTitle: '', type: 'form', children: [{ list: [baseFieldData] }] });
            }
          }
        }
      }, { notForEachSubform: true });
    },

    getTablePrintConfig(i) {
      let obj;
      // list.forEach(i => {
      if (i.type === 'subform' || i.type === 'linkForm') {
        if (!i.options.printHide && i.value && i.value.length && i.subform && i.subform.length) {
          obj = { subTitle: i.name, type: 'table', keyword: i.key, children: [] };
          const foot = this.getStatistics(i);
          i.subform.forEach(j => {
            if (!j.options || !j.options.printHide) {
              const child = { title: j.name, keyword: j.key };
              obj.children.push(child);
            }
          });
          if (foot && foot.length) obj.foot = foot;
        }
      } else if (i.type === 'associatedApproval' && !i.options.printHide) {
        obj = { subTitle: i.name, type: 'table', noValidEmpty: true, keyword: i.key, children: [
          { title: '任务类型', keyword: 'type' },
          { title: '摘要', keyword: 'content' },
          { title: '发起人', keyword: 'proposerName' },
          { title: '发起时间', keyword: 'createTime' },
          { title: '当前节点', keyword: 'currentNode' },
          { title: '当前处理人', keyword: 'approvers' },
          { title: '审批时间', keyword: 'approveTime' },
          { title: '流程状态', keyword: 'status' }
        ] };
      }
      // });
      return obj;
    },
    getPrintData(formOptions) {
      const ans = {};
      formOptions.list.forEach(i => {
        if (i.type !== 'subform' && i.type !== 'grid' && i.type !== 'linkForm' && i.type !== 'associatedApproval') {
          ans[i.key] = this.getPrintValue(i);
        }
        if (i.type === 'grid' && i.columns && i.columns.length) {
          i.columns.forEach(j => {
            j.list.forEach(k => {
              ans[k.key] = this.getPrintValue(k);
            });
          });
        }
        if (
          ((i.type === 'subform' || i.type === 'linkForm') && i.value && i.value.length) ||
          (i.type === 'associatedApproval' && !i.options.printHide) &&
          Array.isArray(i.value)
        ) {
          i.value.forEach(data => {
            if (i.type === 'subform' || (i.type === 'linkForm' && i.options.remoteParams.isCustom && data.content)) {
              if (i.type === 'linkForm' && data.content) {
                for (const key of Object.keys(data.content)) {
                  if (key === 'status') {
                    data[key] = processCommonStatus(data.content[key]);
                  } else {
                    data[key] = data.content[key];
                  }
                }
              } else {
                for (const key of Object.keys(data)) {
                  const subElement = i.subform.find(form => form.key === key);
                  if (subElement) {
                    subElement.value = data[key];
                    data[key] = this.getPrintValue(subElement);
                  }
                }
              }
            } else if (i.type === 'associatedApproval') { // 关联表单
              this.setAssociatedApprovalData(data);
            } else {
              // 固定表单
              const type = i.options.remoteParams.type;
              const configData = getConfigData(type);
              if (configData) {
                i.subform.forEach(form => {
                  data[form.key] = this.getLinkFormData(configData, form.key, data[form.key], data);
                });
              }
            }
          });
          ans[i.key] = i.value;
        }
        if (i.type === 'associatedApproval' && (!i.value || !i.value.length)) {
          ans[i.key] = [];
        }
      });
      return ans;
    },
    setAssociatedApprovalData(data) {
      data.type = getTaskType(data.type);
      if (strJsonParse(data.content) && data.content !== '{}') {
        const contentData = strJsonParse(data.content);
        const contentList = [];
        for (const name in contentData) {
          contentList.push(`${name}: ${contentData[name]}`);
        }
        data.content = contentList.join(';');
      } else {
        data.content = '--';
      }
      data.createTime = this.formatTime(data.createTime);
      data.approveTime = this.formatTime(data.approveTime);
      data.status = flowStatus(data.status);
    },
    formatTime(timeStr) {
      if (timeStr) {
        const time = new Date(timeStr).getTime();
        return moment(time).format('YYYY/MM/DD').toString();
      } else {
        return '--';
      }
    },
    getPrintValue(element) {
      if (element.options && element.options.isSecret && !element._isShowSecret) {
        return '******';
      }
      if (element.value === undefined || element.value === null || element.value === '' || (Array.isArray(element.value) && element.value.length === 0)) return '--';
      if (element.type === 'input' || element.type === 'radio' || element.type === 'formulaInput' || element.type === 'textarea') {
        if ((element.type === 'formulaInput' && !element.options.modeType) || (element.type === 'input' && element.options.dataType === 'number')) {
          const precision = element.options.precision;
          if (precision || precision === 0) {
            return Number(Number(element.value).toFixed(precision));
          }
        }
        return element.value;
      } else if (element.type === 'select') {
        if (element.options.multiple && Array.isArray(element.value)) {
          return element.value.map(i => i).join(',');
        } else {
          return element.value;
        }
      } else if (element.type === 'checkbox' && element.value && Array.isArray(element.value)) {
        return element.value.map(i => i).join(',');
      } else if (element.type === 'user' || element.type === 'createUser') {
        if (element.options.multiple && Array.isArray(element.value)) {
          return element.value.map(i => i.userName).join(',');
        } else {
          return typeof element.value === 'string' ? element.value : element.value.userName;
        }
      } else if (element.type === 'department') {
        if (element.options.multiple && Array.isArray(element.value)) {
          return element.value.map(i => i.name).join(',');
        } else {
          return element.value.name;
        }
      } else if (element.type === 'date' || element.type === 'createTime') {
        return format(element.value, this.getFormat(element.options.format));
      } else if (element.type === 'switch') {
        return element.value ? '是' : '否';
      } else if (element.type === 'upAttachment' && Array.isArray(element.value)) {
        return element.value.map(i => i.name).join(',');
      } else if (element.type === 'address' && Array.isArray(element.value)) {
        return element.value.join('-');
      } else if (element.type === 'post') {
        if (Array.isArray(element.value)) {
          const names = element.value.map(i => i.name).join(',');
          return names || '--';
        } else {
          return element.value.name || '--';
        }
      } else if (['titleExplain', 'richEditor'].includes(element.type)) {
        const result = element.value.replace(/<img/g, '<img style="max-width: 100%;max-height: 100%;"');
        return result || '--';
      }
      return element.value || '--';
    },
    getFormat(format) {
      if (!format) return 'YYYY/MM/DD HH:mm:ss';
      format = format.replace('yyyy', 'YYYY');
      format = format.replace('dd', 'DD');
      return format;
    },
    getLinkFormData(configData, key, data, row) {
      if (data === undefined || data === null || data === '' || (Array.isArray(data) && data.length === 0)) return '--';
      if (configData && configData.fieldsProp && configData.fieldsProp[key]) {
        const fieldProp = configData.fieldsProp[key];
        if (fieldProp.type === 'price') {
          return fieldProp.unit === '分' ? data / 100 : data;
        } else if (fieldProp.type === 'filter') {
          const params = fieldProp.filterParams || null;
          return fieldProp.filter(data, params);
        } else if (fieldProp.type === 'date') {
          return fieldProp.filter(data, fieldProp.format);
        } else if (fieldProp.type === 'allPersonNum') {
          return data - row.unfillNum + `/${data}`;
        } else if (fieldProp.type === 'dateRange') {
          return this.getRangeDate(row, configData, key);
        } else if (fieldProp.type === 'contractEffectStartDate') {
          if (row.contractDate === 1 || row.contractDate === '年框类' || row.contractDate === null) {
            return format(row.contractEffectStartDate, 'YYYY/MM/DD') + this.handleLimit(row) + format(row.contractEffectEndDate, 'YYYY/MM/DD');
          } else {
            return format(row.pushTime, 'YYYY/MM/DD');
          }
        }
      }
      return data;
    },
    getRangeDate(item, configData, key) {
      const data = configData.fieldsProp[key];
      if (item[data.start] && item[data.end]) {
        return `${data.filter(item[data.start], data.format)} - ${data.filter(item[data.end], data.format)}`;
      }
      return '--';
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    // 获取统计字段
    getStatistics(element) {
      const statistics = element.options.statistics || [];
      const keys = [];
      if (element.type === 'subform' || (element.type === 'linkForm' && element.options.remoteParams.isCustom)) {
        statistics.forEach(i => {
          const item = element.subform.find(j => j.key === i);
          if (item && !item.options.printHide) keys.push({ title: item.name, data: null, mathKeyword: i, type: 'money' });
        });
      } else if (element.options.remoteParams) {
        const configData = getConfigData(element.options.remoteParams.type);
        if (configData && configData.numberField) {
          configData.numberField.forEach(i => {
            const hasKey = element.subform.some(sub => sub.key === i.key);
            if (hasKey) keys.push({ title: i.name, data: null, mathKeyword: i.key, type: 'money' });
          });
        }
      }
      return keys;
    }
  }
};
